<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v8;


use app\api\model\Authority;
use think\Controller;
use think\Exception;
use think\Request;
use  think\Db;


class Interactive extends Controller
{
    protected $model;
    protected $us;
    
    
    public function _initialize()
    {
        $this->model=new Authority();
        $this->us   =Authority::check(1);
        
    }
    
    /**
     * 辅助交互系统
     */
    public function auxiliaryInteractive()
    {
        
        $data=Request::instance()->post();
        if (empty($data['ids'])) {
            r_date(null, 300, '参数错误');
        }
        $op       =json_decode($data['ids'], true);
        $aggregate=[];
        if ($op) {
            $detailedId=array_column($op, 'id');
            foreach ($op as $ke=>$v) {
                $serial=db('detailed')->where('detailed_id', $v['id'])->value('serial');
                if ($serial) {
                    $auxiliary_relation=db('auxiliary_relation')
                        ->join('auxiliary_interactive', 'auxiliary_interactive.id=auxiliary_relation.auxiliary_interactive_id and  auxiliary_interactive.parents_id=0', 'left')
                        ->where('auxiliary_relation.serial_id', $serial)
                        ->where('auxiliary_interactive.pro_types', 0)
                        ->field('auxiliary_interactive.title,auxiliary_interactive.id')
                        ->select();
                    
                    foreach ($auxiliary_relation as $k=>$item) {
                        $auxiliary_relation[$k]['data']=db('auxiliary_interactive')->where('parents_id', $item['id'])->where('pro_types', 0)->field('title,id')->select();
                        $auxiliaryRelation             =db('auxiliary_relation')->join('detailed', 'detailed.serial=auxiliary_relation.serial_id', 'left')->where('auxiliary_relation.auxiliary_interactive_id', $item['id'])->whereIn('detailed.detailed_id', $detailedId)->field('detailed_id,detailed_title')->select();
                        
                        $auxiliary_relation[$k]['auxiliaryInteractiveId']=$auxiliaryRelation;
                    }
                    
                    if ($auxiliary_relation) {
                        
                        $aggregate[]=$auxiliary_relation[0];
                    }
                }
                
                
            }
        }
        
        r_date(array_values(array_unique($aggregate, SORT_REGULAR)), 200);
//        res_date($aggregate, 200);
        
    }
    
    /**
     * 辅助交互系统三级
     */
    public function auxiliaryInteractiveInfo()
    {
        
        $data              =Request::instance()->post();
        $auxiliary_relation=db('auxiliary_interactive')->where('parents_id', $data['id'])->field('title,id,shot,acceptance_criteria,grade,picture_label,picture_url,materials_used,materials_consumption')->select();
        foreach ($auxiliary_relation as $k=>$item) {
            $auxiliary_relation[$k]['picture_url']=empty($item['picture_url'])? [] : unserialize($item['picture_url']);
        }
        $nodeList=[];
        if ($data['nodeId'] != 0) {
            $results=send_post(UIP_SRC . "/support-v1/node/info?node_id=" . $data['nodeId'], [], 2);
            $results=json_decode($results, true);
            
            if ($results['code'] == 200) {
                $nodeList=$results['data'];
                foreach ($nodeList as $l=>$item) {
                    $auxiliary_delivery_node   =db('auxiliary_delivery_node')->where('node_id', $item['id'])->field('state,reason')->find();
                    $nodeList[$l]['state']     =$auxiliary_delivery_node['state'];
                    $nodeList[$l]['reason']    =$auxiliary_delivery_node['reason'];
                    $nodeList[$l]['created_at']=empty($item['updated_at'])? date('Y-m-d H:i:s', $item['created_at']) : date('Y-m-d H:i:s', $item['updated_at']);
                }
                
            }
        }
        r_date(['data'=>$auxiliary_relation, 'nodeList'=>$nodeList], 200);
        
    }
    
    
    public function toExamine()
    {
        $data                   =Request::instance()->post();
        $auxiliary_delivery_node=db('auxiliary_delivery_node')->where('node_id', $data['id'])->update(['state'=>$data['state'], 'reason'=>$data['reason'], 'audit_time'=>time()]);
        if ($auxiliary_delivery_node) {
            r_date(null, 200);
        }
        r_date(null, 300);
    }
    
    /**
     * 辅助交互系统全部
     */
    public function auxiliaryInteractiveAll()
    {
        $data                 =Request::instance()->post();
        $auxiliary_interactive=db('auxiliary_interactive')
            ->where('pro_types', 0)
            ->where('parents_id', 0)
            ->where('IF(category=2,user_id=' . $this->us['user_id'] . ',user_id=0)')
            ->field('title,id')
            ->select();
        
        foreach ($auxiliary_interactive as $k=>$item) {
            $auxiliaryInteractive=db('auxiliary_interactive');
            if (isset($data['title']) && $data['title'] != '') {
                $auxiliaryInteractive->whereLike('title', "%{$data['title']}%");
            }
            $po=$auxiliaryInteractive->where('parents_id', $item['id'])->where('pro_types', 0)->field('title,id')->select();
            if (empty($po)) {
                unset($auxiliary_interactive[$k]);
            } else{
                $auxiliary_interactive[$k]['data']=$po;
            }
            
        }
        r_date(array_merge($auxiliary_interactive), 200);
    }
    
    /**
     * 辅助交互系统自定义添加
     */
    public function auxiliaryInteractiveAdd()
    {
        $data=Request::instance()->post();
        
        db()->startTrans();
        try {
            $parents_id =db('auxiliary_interactive')->insertGetId(
                [
                    'title'     =>$data['type'],
                    'parents_id'=>0,
                    'category'  =>2,
                    'user_id'   =>$this->us['user_id'],
                ]
            );
            $parents_ids=db('auxiliary_interactive')->insertGetId(
                [
                    'title'     =>$data['name'],
                    'parents_id'=>$parents_id,
                    'category'  =>2,
                    'user_id'   =>$this->us['user_id'],
                ]
            );
            if ($parents_ids) {
                db('auxiliary_interactive')->insertGetId(
                    [
                        'title'                =>$data['title'],
                        //'node'                 =>$data['node'],
                        'shot'                 =>$data['shot'],
                        'acceptance_criteria'  =>$data['acceptance_criteria'],
                        'grade'                =>$data['grade'],
                        'picture_url'          =>!empty($data['picture_url'])? serialize(json_decode($data['picture_url'], true)) : '',//图片,
                        'materials_used'       =>isset($data['materials_used'])? $data['materials_used'] : '',
                        'materials_consumption'=>isset($data['materials_consumption'])? $data['materials_consumption'] : '',
                        'parents_id'           =>$parents_ids,
                        'category'             =>2,
                        'user_id'              =>$this->us['user_id'],
                    ]
                );
                $auxiliary_interactive=db('auxiliary_interactive')
                    ->where('pro_types', 0)
                    ->where('parents_id', 0)
                    ->where('id', $parents_id)
                    ->where('user_id', $this->us['user_id'])
                    ->field('title,id')
                    ->select();
                foreach ($auxiliary_interactive as $k=>$item) {
                    $po                               =db('auxiliary_interactive')->where('parents_id', $item['id'])->where('pro_types', 0)->field('title,id')->select();
                    $auxiliary_interactive[$k]['data']=$po;
                }
            }
            db()->commit();
            r_date($auxiliary_interactive, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
        
    }
    /*
     * 已添加的自定义
     */
    /**
     * @return mixed
     */
    public function getCustom()
    {
        $auxiliary_interactive=db('auxiliary_interactive')
            ->where('pro_types', 0)
            ->where('parents_id', 0)
            ->where('user_id', $this->us['user_id'])
            ->field('title,id')
            ->select();
        foreach ($auxiliary_interactive as $k=>$item) {
            $po                               =db('auxiliary_interactive')->where('parents_id', $item['id'])->where('pro_types', 0)->field('title,id')->select();
            $auxiliary_interactive[$k]['data']=$po;
        }
        r_date($auxiliary_interactive, 200);
    }
    
    /*
     * 交付标准列表
    
    * @return mixed
     */
    public function getCustomList()
    {
      
        $data        =Request::instance()->get();
        $envelopes_id=db('envelopes');
        if (isset($data['envelopes_id']) && $data['envelopes_id'] != 0) {
            $envelopes_id->where('envelopes_id', $data['envelopes_id']);
        } else{
            $envelopes_id->where('type', 1);
        }
        $envelopes_id=$envelopes_id->where('ordesr_id', $data['order_id'])->value('envelopes_id');
        
        $capital=db('capital')->where('envelopes_id', $envelopes_id)
            ->where('types', 1)
            ->field('class_b,capital_id')
            ->select();
        
        foreach ($capital as $k=>$item) {
            $po           =db('auxiliary_project_list')->where('capital_id', $item['capital_id'])->whereNull('delete_time')->field('auxiliary_id,id')->select();
            $auxiliary_ids=array_unique(array_column($po, 'id'));
            if ($po) {
                foreach ($po as $l=>$key) {
                    $capital[$k]['auxiliary_id'] =$key['id'];
                    $capital[$k]['auxiliary_ids']=implode($auxiliary_ids, ',');
                    $capital[$k]['data'][]       =db('auxiliary_interactive')->where('id', $key['auxiliary_id'])->field('id,title')->find();
                    $auxiliary_interactive       =db('auxiliary_interactive')
                        ->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.auxiliary_interactive_id=auxiliary_interactive.id', 'left')
                        ->where('auxiliary_delivery_schedule.auxiliary_project_list_id', $key['id'])
                        ->whereNull('auxiliary_delivery_schedule.delete_time')
                        ->field('auxiliary_interactive.id, auxiliary_interactive.title, auxiliary_delivery_schedule.id as auxiliary_delivery_schedule_id')->select();
                    foreach ($auxiliary_interactive as $p=>$value) {
                        $auxiliary_delivery_node=db('auxiliary_delivery_node')->where('auxiliary_delivery_schedul_id', $value['auxiliary_delivery_schedule_id'])->field('state,node_id')->select();
                        $auxiliaryNodeId        =array_column($auxiliary_delivery_node, 'state');
                        $auxiliaryNodeNode      =array_column($auxiliary_delivery_node, 'node_id');
                        if ($auxiliaryNodeId) {
                            if (in_array(2, $auxiliaryNodeId)) {
                                $auxiliary_interactive[$p]['state']  =2;
                                $auxiliary_interactive[$p]['node_id']=implode(',', $auxiliaryNodeNode);
                                
                            } elseif (in_array(0, $auxiliaryNodeId)){
                                $auxiliary_interactive[$p]['state']  =0;
                                $auxiliary_interactive[$p]['node_id']=implode(',', $auxiliaryNodeNode);
                                
                            } else{
                                $auxiliary_interactive[$p]['state']  =1;
                                $auxiliary_interactive[$p]['node_id']=implode(',', $auxiliaryNodeNode);
                            }
                        } else{
                            $auxiliary_interactive[$p]['state']  =3;
                            $auxiliary_interactive[$p]['node_id']=0;
                        }
                        
                        
                    }
                    $capital[$k]['data'][$l]['data']=array_merge($auxiliary_interactive);
                }
            } else{
                $capital[$k]['data']=[];
            }
            
        }
        r_date(array_values($capital), 200);
    }
    
    /*
     * 辅助交互系统编辑
     */
    public function AssistantEditor()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $standardJson=json_decode($data['standardJson'], true);
            foreach ($standardJson as $k=>$item) {
                if ($item['auxiliary_id'] == 0 && !empty($item['data'])) {
                    foreach ($item['data'] as $value) {
                        $auxiliary_project_list=db('auxiliary_project_list')->insertGetId(['auxiliary_id'=>$value['id'], 'capital_id'=>$item['capital_id'], 'order_id'=>$data['order_id'], 'created_time'=>time()]);
                        foreach ($value['data'] as $datum) {
                            db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id'=>$datum['id'], 'auxiliary_project_list_id'=>$auxiliary_project_list]);
                        }
                    }
                } elseif ($item['auxiliary_id'] != 0 && empty($item['data'])){
                    
                    if ($item['auxiliary_id'] != 0) {
                        db('auxiliary_project_list')->join('auxiliary_delivery_schedule', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id', 'left')->whereIn('auxiliary_project_list.id', $item['auxiliary_ids'])->update(['auxiliary_project_list.delete_time'=>time(), 'auxiliary_delivery_schedule.delete_time'=>time()]);
                        
                    }
                    
                } elseif ($item['auxiliary_id'] != 0 && !empty($item['data'])){
                    $auxiliary_project_list=db('auxiliary_delivery_schedule')
                        ->join('auxiliary_project_list', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id', 'left')
                        ->where(['auxiliary_project_list.capital_id'=>$item['capital_id']])
                        ->whereNull('auxiliary_project_list.delete_time')
                        ->select();
                    
                    if (empty($auxiliary_project_list)) {
                        foreach ($item['data'] as $value) {
                            $auxiliary_project_list=db('auxiliary_project_list')->insertGetId(['auxiliary_id'=>$value['id'], 'capital_id'=>$item['capital_id'], 'order_id'=>$data['order_id'], 'created_time'=>time()]);
                            foreach ($value['data'] as $datum) {
                                db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id'=>$datum['id'], 'auxiliary_project_list_id'=>$auxiliary_project_list]);
                            }
                        }
                    } else{
                        
                        $jsonId=array_column($item['data'], 'id');
                        
                        $auxiliaryId=array_unique(array_column($auxiliary_project_list, 'auxiliary_id'));
                        //获取差集数组
                        if (count($jsonId) > count($auxiliaryId)) {
                            $result=array_diff($jsonId, $auxiliaryId);
                        } else{
                            $result=array_diff($auxiliaryId, $jsonId);
                        }
                        
                        if (empty($result)) {
                            
                            foreach ($item['data'] as $vl) {
                                $auxiliar=db('auxiliary_delivery_schedule')->join('auxiliary_project_list', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id', 'left')->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->where(['auxiliary_project_list.auxiliary_id'=>$vl['id'], 'auxiliary_project_list.capital_id'=>$item['capital_id'], 'auxiliary_project_list.order_id'=>$data['order_id']])->select();
                                
                                $jsonIdNex     =array_column($vl['data'], 'id');
                                $auxiliaryIdNex=array_unique(array_column($auxiliar, 'auxiliary_interactive_id'));
                                $b             =array_intersect($jsonIdNex, $auxiliaryIdNex);
                                
                                if (!empty($b)) {
                                    db('auxiliary_delivery_schedule')->whereNotIn('auxiliary_interactive_id', $b)->where('auxiliary_project_list_id', $auxiliar[0]['auxiliary_project_list_id'])->update(['delete_time'=>time()]);
                                    
                                }
                                if (empty($b)) {
                                    db('auxiliary_delivery_schedule')->whereIn('auxiliary_interactive_id', $auxiliaryIdNex)->where('auxiliary_project_list_id', $auxiliar[0]['auxiliary_project_list_id'])->update(['delete_time'=>time()]);
                                }
                                $results=array_merge(array_diff($jsonIdNex, $auxiliaryIdNex));
                                if (!empty($results)) {
                                    foreach ($results as $l) {
                                        db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id'=>$l, 'auxiliary_project_list_id'=>$auxiliar[0]['auxiliary_project_list_id']]);
                                        
                                    }
                                }
                                
                                
                            }
                            
                        }
                        
                        
                        if (!empty($result)) {
                            
                            $o=array_merge(array_intersect($jsonId, $auxiliaryId));
                            db('auxiliary_project_list')->join('auxiliary_delivery_schedule', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id', 'left')->whereNotIn('auxiliary_project_list.auxiliary_id', $o)->where('capital_id', $item['capital_id'])->update(['auxiliary_project_list.delete_time'=>time(), 'auxiliary_delivery_schedule.delete_time'=>time()]);
                           
                            foreach ($item['data'] as $v) {
                                foreach ($result as $l) {
                                    if ($v['id'] == $l) {
                                        $auxiliary_project_list=db('auxiliary_project_list')->insertGetId(['auxiliary_id'=>$v['id'], 'capital_id'=>$item['capital_id'], 'order_id'=>$data['order_id'], 'created_time'=>time()]);
                                        foreach ($v['data'] as $datum) {
                                            db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id'=>$datum['id'], 'auxiliary_project_list_id'=>$auxiliary_project_list]);
                                        }
                                    }
                                    
                                }
                                $auxiliar=db('auxiliary_delivery_schedule')->join('auxiliary_project_list', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id', 'left')->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->where(['auxiliary_project_list.auxiliary_id'=>$v['id'], 'auxiliary_project_list.capital_id'=>$item['capital_id'], 'auxiliary_project_list.order_id'=>$data['order_id']])->select();
                                
                                $jsonIdNex=array_column($v['data'], 'id');
                                
                                $auxiliaryIdNex=array_unique(array_column($auxiliar, 'auxiliary_interactive_id'));
                                if (count($auxiliaryIdNex) > count($jsonIdNex)) {
                                    
                                    $c=array_diff($auxiliaryIdNex, $jsonIdNex);
                                    db('auxiliary_delivery_schedule')->whereIn('auxiliary_interactive_id', $c)->where('auxiliary_project_list_id', $auxiliar[0]['auxiliary_project_list_id'])->update(['delete_time'=>time()]);
                                }
                                
                                $m1=array_diff($jsonIdNex, $auxiliaryIdNex);
                                
                                if (!empty($m1)) {
                                    if ($auxiliar) {
                                        foreach ($m1 as $l1) {
                                            db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id'=>$l1, 'auxiliary_project_list_id'=>$auxiliar[0]['auxiliary_project_list_id']]);
                                            
                                        }
                                    }
                                    
                                }
                                
                            }
                        }
                    }
                }
                
               
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    public function delete()
    {
        $data                 =Request::instance()->post();
        $auxiliary_interactive=db('auxiliary_interactive')->where('id', $data['id'])->value('parents_id');
        db('auxiliary_interactive')->where('id', $auxiliary_interactive)->update(['pro_types'=>1]);
        db('auxiliary_interactive')->where('id', $data['id'])->update(['pro_types'=>1]);
        db('auxiliary_interactive')->where('parents_id', $data['id'])->update(['pro_types'=>1]);
        r_date(null, 200);
    }
    
    public function addNode()
    {
        db()->startTrans();
        Db::connect(config('database.db2'))->startTrans();
        $data=Request::instance()->post();
        try {
            $params  =request()->only(['order_id', 'title', 'describe', 'lng', 'lat', 'address']);
            $resource=json_decode($data['resource'], true);
            if (!empty($resource)) {
                $params['resource_ids']=implode(',', $this->addResourceIds($resource));
            }
            $params['describe']   =$data['describe'];
            $params['user_id']    =$this->us['user_id'];
            $params['type']       =2;
            $params['status']     =1;
            $params['distinguish']=1;
            $params['created_at'] =time();
            $params['updated_at'] =time();
            $capital_id           =$data['projectId'];
            $tagId                =$data['tagId'];
            if ($data['nodeId'] == 0) {
                if ($orderNode=Db::connect(config('database.db2'))->table('app_user_order_node')->insertGetId($params)) {
                    if ($capital_id != 0) {
                        $auxiliary_delivery_schedule_id=db('auxiliary_project_list')
                            ->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')
                            ->where('auxiliary_project_list.capital_id', $capital_id)
                            ->where('auxiliary_delivery_schedule.auxiliary_interactive_id', $tagId)
                            ->whereNull('auxiliary_delivery_schedule.delete_time')
                            ->value('auxiliary_delivery_schedule.id');
                        db('auxiliary_delivery_node')->insertGetId(['auxiliary_delivery_schedul_id'=>$auxiliary_delivery_schedule_id, 'node_id'=>$orderNode, 'mast_id'=>$this->us['user_id'], 'state'=>1]);
                    }
                    Db::connect(config('database.db2'))->commit();
                    db()->commit();
                    
                    
                }
            } else{
                if (Db::connect(config('database.db2'))->table('app_user_order_node')->where('id', $data['nodeId'])->update($params)) {
                    Db::connect(config('database.db2'))->commit();
                    db()->commit();
                    
                };
                
            }
            $auxiliary_delivery_node=db('auxiliary_delivery_node')
                ->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.id=auxiliary_delivery_node.auxiliary_delivery_schedul_id', 'left')
                ->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')
                ->whereNull('auxiliary_delivery_schedule.delete_time')
                ->where('auxiliary_project_list.capital_id', $capital_id)
                ->column('auxiliary_delivery_node.node_id');
//                array_push($auxiliary_delivery_node,$orderNode);
            r_date(implode(',', $auxiliary_delivery_node), 200);
            
        } catch (\Exception $e) {
            
            Db::connect(config('database.db2'))->rollBack();
            db()->rollBack();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /**
     * 添加资源返回ID
     * @param $resources
     * @return array
     */
    public function addResourceIds($resources)
    {
        
        $resource_ids=[];
        foreach ($resources as $item) {
            if (!isset($item['mime_type']) || !isset($item['file_path'])) {
                r_date(null, 300, '资源格式错误');
            }
            $info=Db::connect(config('database.db2'))->table('common_resource')->where('path', $item['file_path'])->find();
            
            if ($info !== null) {
                $resource_ids[]=$info['id'];
            } else{
                $resource_ids[]=Db::connect(config('database.db2'))->table('common_resource')->insertGetId(['mime_type'=>$item['mime_type'], 'path'=>$item['file_path'], 'size'=>$item['size'] ?? 0, 'created_at'=>time()]);
            }
        }
        return $resource_ids;
    }


    
}